//
//  ListTableViewController.swift
//  私人通讯录
//
//  Created by zq on 2020/10/23.
//

import UIKit

class ListTableViewController: UITableViewController {
    
    var personList = [Person]()

    override func viewDidLoad() {
        super.viewDidLoad()

        loadData { (list) in
            print(list)
            self.personList += list
            self.tableView.reloadData()
        }
    }

    /// 模拟数据
    private func loadData(completion:@escaping([Person])->()) {
        DispatchQueue.global().async {
            print("加载数据中")
            var arrayMan = [Person]()
            for i in 0..<20{
                let p = Person()
                p.name = "zhangsan \(i)"
                p.phone = "183" + String(format: "%06d", arc4random_uniform(100000000))
                p.title = "boss"
                arrayMan.append(p)
            }
            DispatchQueue.main.async {
                completion(arrayMan)
            }
        }
    }
    /// 使用storyboard 做页面跳转都会回调这方法
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! DetailTableViewController
        if let indexPath = sender as? IndexPath {
            vc.person = self.personList[indexPath.row]
            vc.complationResultCallBack = {
                self.tableView.reloadRows(at: [indexPath], with: .automatic)
            }
        }else{
            // vc.complationResultCallBack vc对complationResultCallBack强引用
            vc.complationResultCallBack = { [weak vc] in//闭包中又出现了vc说明闭包对vc强引用 所以出现了 内存泄漏
                guard let p = vc?.person else { //vc? vc变成弱引用之后,vc随之都可能为nil,
                    return
                }
                self.personList.insert(p, at: 0)
                self.tableView.reloadData()
            }
            
        }
        
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        performSegue(withIdentifier: "list2Detail", sender: indexPath)
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return personList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
        cell.textLabel?.text = personList[indexPath.row].name
        cell.detailTextLabel?.text = personList[indexPath.row].phone
        return cell
    }
    
    
    @IBAction func addPerson(_ sender: Any) {
        performSegue(withIdentifier: "list2Detail", sender: nil)
    }
    
    

}
